#include "Stdafx.h"
#include "AppWinMFC.h"
#include "ChildView.h"
#include "MainFrm.h"
#include <mmsystem.h>

// CChildView
//bool ViewKeyboard[1024];

//------------------------------------------------------------------------------------
CChildView::CChildView(): /*m_OgreRoot(0), m_Window(0), m_SceneManager(0),*/
m_ObjCounter(0), m_OgreInitialised(false), m_LastKeyEventTime(0), m_RenderStop(false), m_ScreenResize(false)
{
    m_FrameCounter = 0;
    m_TotalFrameTime = 0;
    m_CurrentCursor = CURSOR_ARROW;
    m_CursorHidden = FALSE;

//     for(int i = 0;i < 1024;i++) 
//         ViewKeyboard[i] = false;

 //   gClientRootRegisterRootListener(this);
}
//------------------------------------------------------------------------------------
CChildView::~CChildView()
{
    //gClientRootUnRegisterRootListener(this);
}
//------------------------------------------------------------------------------------
static Apo::Vector3 oldCamPos = Apo::Vector3::ZERO;

//bool CChildView::frameStarted(const FrameEvent& evt)
//{
//     DisplayFPS(evt.timeSinceLastFrame);
//     gClientRootGetViewport()->UpdateAutoCameraPosition(evt.timeSinceLastFrame);
//     if(theApp.m_OgitorsRoot->GetTerrainEditor())
// 	    theApp.m_OgitorsRoot->GetTerrainEditor()->SetEditDirection(ViewKeyboard[VK_SHIFT]);
// 
//     theApp.m_OgitorsRoot->Update(evt.timeSinceLastFrame);
// 
//     Apo::Vector3 campos = theApp.m_OgitorsRoot->GetViewport()->GetCameraEditor()->GetCamera()->getDerivedPosition();
//     if(oldCamPos != campos)
//     {
//        CString strCam;
//        strCam.Format(_T("Camera Position: X:%.2f, Y:%.2f, Z:%.2f"),campos.x,campos.y,campos.z);
//        ((CMainFrame*)theApp.GetMainWnd())->UpdateStatusBarPane(ID_STATUSBAR_PANE1,strCam);
// 
//        oldCamPos = campos;
//     }

 //   return true;
//}

//bool CChildView::frameRenderingQueued(const FrameEvent& evt)
//{
	//(void)evt; 
	//theApp.m_OgitorsRoot->frameRenderingQueued(evt.timeSinceLastFrame);
//	return true; 
// }

//------------------------------------------------------------------------------------
void CChildView::SetupOgre(void)
{
    //CRect   rect;
    //GetClientRect(&rect);
// 
}
//------------------------------------------------------------------------------------
void CChildView::OnTerminateScene()
{
    TerminateScene();
}

void CChildView::OnAfterLoadScene()
{
    ((CMainFrame *)theApp.GetMainWnd())->SetCameraPositions();

//     CString appTitle;
//     appTitle.LoadString(IDR_MAINFRAME);
//     appTitle += _T(" - ") + CString(theApp.m_OgitorsRoot->GetProjectOptions()->ProjectName.c_str()) + _T(".ogscene");
//     ((CMainFrame *)theApp.GetMainWnd())->SetTitle(appTitle);
//     theApp.GetMainWnd()->Invalidate();
// 
//     m_SceneManager = theApp.m_OgitorsRoot->GetSceneManager();
// 
//     ((CMainFrame *)(theApp.GetMainWnd()))->getCAddEntityWnd()->m_wndEntityView.SetupOgre();
// 
//     CString strCam;
//     Apo::Vector3 pos = theApp.m_OgitorsRoot->GetViewport()->GetCameraEditor()->GetCamera()->getDerivedPosition();
// 
//     strCam.Format(_T("Camera Position: X:%.2f, Y:%.2f, Z:%.2f"),pos.x,pos.y,pos.z);
//     ((CMainFrame*)theApp.GetMainWnd())->UpdateStatusBarPane(ID_STATUSBAR_PANE1,strCam);
// 
//     CTerrainEditor *terraineditor = theApp.m_OgitorsRoot->GetTerrainEditor();
//     if(terraineditor) 
//         ((CMainFrame *)theApp.GetMainWnd())->UpdateTerrainOptions(terraineditor);
// 
//     theApp.m_FPSTimer = FPSLIST[theApp.m_FPSID];
// 
//     OgitorsSpecialKeys keys;
//     keys.SPK_ALT = VK_MENU;
//     keys.SPK_TAB = VK_TAB;
//     keys.SPK_DELETE = VK_DELETE;
//     keys.SPK_SHIFT = VK_SHIFT;
//     keys.SPK_CTRL = VK_CONTROL;
//     CViewportEditor::SetKeyboard(ViewKeyboard, keys);
// 
//     ((CMainFrame *)(theApp.GetMainWnd()))->getCAddEntityWnd()->m_wndEntityView.LoadEditorObjects();
// 
//     m_Window->setActive(true);
//     m_Window->update();
//     SetFocus();
}
//------------------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(CChildView, CWnd)
	ON_WM_PAINT()
	ON_WM_SIZE()
	ON_WM_SETFOCUS()
	ON_WM_KILLFOCUS()
	ON_WM_KEYDOWN()
	ON_WM_KEYUP()
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
	ON_WM_RBUTTONDOWN()
	ON_WM_RBUTTONUP()
	ON_WM_MBUTTONDOWN()
	ON_WM_MBUTTONUP()
	ON_WM_MOUSEWHEEL()
	ON_WM_MOUSEMOVE()
	ON_WM_MOUSELEAVE()
	ON_WM_ERASEBKGND()
	ON_MESSAGE(WM_UPDATEOGRE,OnUpdateOgre)
	ON_MESSAGE(WM_RELOADUSERRESOURCES,ReloadUserResources)
END_MESSAGE_MAP()
//------------------------------------------------------------------------------------
BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs) 
{
	if (!CWnd::PreCreateWindow(cs))
		return FALSE;

	cs.dwExStyle |= WS_EX_CLIENTEDGE;
	cs.style &= ~WS_BORDER;
	cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS, 
		::LoadCursor(NULL, IDC_ARROW), reinterpret_cast<HBRUSH>(COLOR_WINDOW+1), NULL);

	return TRUE;
}
//------------------------------------------------------------------------------------
BOOL CChildView::OnEraseBkgnd(CDC* pDC)
{
    return TRUE;
}

//------------------------------------------------------------------------------------
#include "RenderEngineSystem.h"

void CChildView::OnPaint() 
{
	CPaintDC dc(this); // device context for painting
	CString msgstr = _T("Initializing OGRE...");
    CRect rc;
    GetClientRect(&rc);
	Apo::String a;
	if (ClientRoot::getInstance().GetRenderSystemPoint())
	{
	ClientRoot::getInstance().GetRenderSystemPoint()->updata(0);
	}

// 	if(m_OgreInitialised&&theApp.m_OgitorsRoot->IsSceneLoaded()&&!m_RenderStop)
// 	{
//         if(rc.Width() > 0 && rc.Height() > 0)
//         {
//             if(((CMainFrame*)theApp.GetMainWnd())->getCAddEntityWnd()->GetUpdateNeeded())
//             {
//                 ((CMainFrame*)theApp.GetMainWnd())->getCAddEntityWnd()->GetRenderWindow()->setActive(true);
//             }
// 
//             if(gClientRootIsClearScreenNeeded())
//             {
//                 Camera *clearcam = gClientRootGetSceneManager()->createCamera("sbtClearCam");
//                 clearcam->setNearClipDistance(0.0001f);
//                 clearcam->setFarClipDistance(0.0002f);
//                 clearcam->lookAt(0,-1,0);
//                 gClientRootGetRenderWindow()->addViewport(clearcam,0);
//             }
// 
//             m_OgreRoot->renderOneFrame();
// 
//             if(gClientRootIsClearScreenNeeded())
//             {
//                 gClientRootGetRenderWindow()->removeViewport(0);
//                 gClientRootGetSceneManager()->destroyCamera("sbtClearCam");
//                 gClientRootClearScreenBackground(false);
//             }
// 
//             if(((CMainFrame*)theApp.GetMainWnd())->getCAddEntityWnd()->GetUpdateNeeded())
//             {
//                 ((CMainFrame*)theApp.GetMainWnd())->getCAddEntityWnd()->GetRenderWindow()->setActive(false);
//                 ((CMainFrame*)theApp.GetMainWnd())->getCAddEntityWnd()->SetUpdateNeeded(false);
//             }
//         }
// 	}
// 	else 
// 	{
// 	 if(m_OgreInitialised &&!theApp.m_OgitorsRoot->IsSceneLoaded())
// 	    msgstr = _T("Please load a Scene File...");
// 	 if(m_RenderStop) 
// 	    msgstr = _T("Device Lost...");
// 	 
// 	 CBrush brush(RGB(0,0,0));
// 	 dc.FillRect(&rc,&brush);
// 	 dc.SetBkColor(RGB(0,0,0));
// 	 dc.SetTextColor(RGB(120,120,120));
// 	 dc.DrawText(msgstr,msgstr.GetLength(),&rc,DT_VCENTER | DT_CENTER | DT_SINGLELINE);
// 	}
}
//------------------------------------------------------------------------------------
LRESULT CChildView::OnUpdateOgre(WPARAM wParam, LPARAM lParam)
{
    OnPaint();

	//((CMainFrame*)theApp.GetMainWnd())->getCAddEntityWnd()->m_wndEntityView.OnPaint();
	

    return 0;
}
//------------------------------------------------------------------------------------
void CChildView::OnSize(UINT nType, int cx, int cy)
{
    m_ScreenResize = true;
	CWnd::OnSize(nType, cx, cy);

    CRect rect; 
    GetClientRect(&rect);
//     if (m_Window) 
//     { 
//         // notify "render window" instance 
//         m_Window->windowMovedOrResized(); 
// 
//         if(gClientRootIsSceneLoaded())
//             gClientRootRenderWindowResized();
//     }
//     m_ScreenResize = false;
}
//------------------------------------------------------------------------------------
void CChildView::OnSetFocus(CWnd* pOldWnd)
{
//     for(int i = 0;i < 1024;i++) 
//         ViewKeyboard[i] = false;
    CWnd::OnSetFocus(pOldWnd);
}
//------------------------------------------------------------------------------------
void CChildView::OnKillFocus(CWnd* pNewWnd)
{
//     for(int i = 0;i < 1024;i++) 
//         ViewKeyboard[i] = false;
//     if(theApp.m_OgitorsRoot && theApp.m_OgitorsRoot->GetTerrainEditor()) 
//         theApp.m_OgitorsRoot->GetTerrainEditor()->StopEdit();
//     CWnd::OnKillFocus(pNewWnd);
}
//------------------------------------------------------------------------------------
void CChildView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    //theApp.m_OgitorsRoot->OnKeyDown(nChar);
}
//------------------------------------------------------------------------------------
void CChildView::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    //theApp.m_OgitorsRoot->OnKeyUp(nChar);
}
//------------------------------------------------------------------------------------
unsigned int CChildView::GetMouseButtons(unsigned int flags)
{
    unsigned int buttons = 0;
    if(flags & MK_LBUTTON)
        buttons |= OMB_LEFT;
    if(flags & MK_RBUTTON)
        buttons |= OMB_RIGHT;
    if(flags & MK_MBUTTON)
        buttons |= OMB_MIDDLE;
    return buttons;
}
//------------------------------------------------------------------------------------
void CChildView::ProcessKeyActions()
{
    unsigned int curtime = timeGetTime();
    unsigned int iTimeDiff = curtime - m_LastKeyEventTime;
    m_LastKeyEventTime = curtime;


}
//------------------------------------------------------------------------------------
//void CChildView::SetCameraMode(PolygonMode mode)
//{
//     if(!theApp.m_OgitorsRoot->GetViewport()->GetCameraEditor()->GetCamera()) return;
//     theApp.m_OgitorsRoot->GetViewport()->GetCameraEditor()->GetCamera()->setPolygonMode(mode);
// }
//------------------------------------------------------------------------------------
void CChildView::DisplayFPS(float time)
{
    m_FrameCounter++;
    m_TotalFrameTime += time;
    m_FrameRate = (float)m_FrameCounter / (float)m_TotalFrameTime ;
    if(m_TotalFrameTime > 2.0f)
    {
        m_TotalFrameTime = 0;
        m_FrameCounter = 0;
        CString strFPS;
        strFPS.Format(_T("Ogre FPS: %.1f"),m_FrameRate);
        ((CMainFrame*)theApp.GetMainWnd())->UpdateStatusBarPane(ID_STATUSBAR_PANE3,strFPS);
    }
}
//----------------------------------------------------------------------------------
bool CChildView::TerminateScene()
{

     Invalidate();
    return true;
}
//--------------------------------------------------------------------------------
LRESULT CChildView::ReloadUserResources(WPARAM wParam, LPARAM lParam)
{

    return TRUE;
}
//-------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
void CChildView::OnLButtonUp(UINT nFlags, CPoint point)
{
    if(GetFocus() != this) SetFocus();

    Apo::Vector2 pos(point.x, point.y);
    
	//theApp.m_OgitorsRoot->OnMouseLeftUp(pos, GetMouseButtons(nFlags));
}
//--------------------------------------------------------------------------------
void CChildView::OnRButtonUp(UINT nFlags, CPoint point)
{
    if(GetFocus() != this) SetFocus();

    Apo::Vector2 pos(point.x, point.y);
    
	//theApp.m_OgitorsRoot->OnMouseRightUp(pos, GetMouseButtons(nFlags));
}
//--------------------------------------------------------------------------------
void CChildView::OnMButtonUp(UINT nFlags, CPoint point)
{
    if(GetFocus() != this) SetFocus();

    Apo::Vector2 pos(point.x, point.y);
    
	//theApp.m_OgitorsRoot->OnMouseMiddleUp(pos, GetMouseButtons(nFlags));
}
//--------------------------------------------------------------------------------

static bool isSettingPos = false;

void CChildView::OnMouseMove(UINT nFlags, CPoint point)
{
	//return;
    if(GetFocus() != this) SetFocus();

    TRACKMOUSEEVENT evt;
    evt.cbSize = sizeof(TRACKMOUSEEVENT);
    evt.dwFlags = TME_LEAVE;
    evt.dwHoverTime = 0;
    evt.hwndTrack = GetSafeHwnd();
    TrackMouseEvent(&evt);

    Apo::Vector2 pos(point.x, point.y);
    
	//theApp.m_OgitorsRoot->OnMouseMove(pos, GetMouseButtons(nFlags));
}
//--------------------------------------------------------------------------------
void CChildView::OnMButtonDown(UINT nFlags, CPoint point)
{
    if(GetFocus() != this) SetFocus();

    Apo::Vector2 pos(point.x, point.y);
    
	//theApp.m_OgitorsRoot->OnMouseMiddleDown(pos, GetMouseButtons(nFlags));
}
//--------------------------------------------------------------------------------
void CChildView::OnRButtonDown(UINT nFlags, CPoint point)
{
    if(GetFocus() != this) SetFocus();

    Apo::Vector2 pos(point.x, point.y);
    
	//theApp.m_OgitorsRoot->OnMouseRightDown(pos, GetMouseButtons(nFlags));
}
//--------------------------------------------------------------------------------
void CChildView::OnLButtonDown(UINT nFlags, CPoint point)
{
    if(GetFocus() != this) SetFocus();

    Apo::Vector2 pos(point.x, point.y);
    
	//theApp.m_OgitorsRoot->OnMouseLeftDown(pos, GetMouseButtons(nFlags));
}
//--------------------------------------------------------------------------------
BOOL CChildView::OnMouseWheel(UINT nFlags, short zDelta, CPoint point)
{
	 //  return true;
    if(GetFocus() != this) SetFocus();

    Apo::Vector2 pos(point.x, point.y);
    
	//theApp.m_OgitorsRoot->OnMouseWheel(pos, zDelta, GetMouseButtons(nFlags));
    
    return true;
}
//--------------------------------------------------------------------------------
void CChildView::OnMouseLeave()
{
	//return;
    if(GetFocus() != this) SetFocus();

    Apo::Vector2 pos(-1, -1);
    
	//theApp.m_OgitorsRoot->OnMouseLeave(pos, 0);
}
//--------------------------------------------------------------------------------
